#!/usr/bin/env python

def xyAverage(t):
	"""
	Returns the average of every x and y of the 't' list (containing couples).
	The complexity of this function is in O(n).
	>>> print xyAverage([(1, 6), (2, 5), (3, 7), (4, 10)])
	(2.5, 7.0)
	>>> print xyAverage([(1, 2), (3, 4)])
	(2.0, 3.0)
	"""
	s = reduce(lambda x, y: (x[0]+y[0], x[1]+y[1]), t)
	return (float(s[0])/len(t), float(s[1])/len(t))

def reg_lin(t):
	"""
	Returns the linear regression of the 't' list (containing couples)
	using the method of least squares.
	The complexity of this function is in O(n).
	>>> print reg_lin([(1, 6), (2, 5), (3, 7), (4, 10)])
	(1.4, 3.5)
	"""
	#pre-compute average values
	(xAv, yAv) = xyAverage(t)
	#start computing x variance and xy covariance
	xVar = xyCovar = 0
	for c in t:
		xVar += (c[0] - xAv) ** 2
		xyCovar += (c[0]-xAv) * (c[1]-yAv)
	#no need to divide both by len(t) - simplification
	a = xyCovar / xVar
	b = yAv - a*xAv
	return (a, b)


if __name__ == "__main__":
	import sys
	if len(sys.argv) >= 2:
		if sys.argv[1] == "--test":
			import doctest
			doctest.testmod()
		elif sys.argv[1] in ["--help", "-h"]:
			print "Please enter points using the following format in stdin:"
			print "each line must consist in two floats separated by a comma."
	else:
		try:
			data = map(lambda x: map(lambda y: float(y.strip()), x.split(",")), sys.stdin.readlines())
			line = reg_lin(data)
			print "Line has equation y=ax+b:"
			print "a", line[0]
			print "b", line[1]
		except ZeroDivisionError as e:
			print "Data set is too small."
		except ValueError as e:
			print e
